package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.BiaoqianmoreBean;
import com.ljfiction.book.Baner.BookdatasBean;
import com.ljfiction.book.Baner.FensiRankBean;
import com.ljfiction.book.Baner.MyBookBean;
import com.ljfiction.book.Baner.Overpage.AuthorBean;
import com.ljfiction.book.Baner.Overpage.OverbookBean;
import com.ljfiction.book.Baner.Overpage.YouLikeBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.ToSubcritDialog;
import com.ljfiction.book.Dialog.TotouweixiaomijinjiaoDialog;
import com.ljfiction.book.MyView.CircularImageView;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.manage.CodeManager;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ReadOverpageActivity extends BaseActivity {

    @BindView(R.id.overpage_bookname)
    TextView overpageBookname;
    @BindView(R.id.overpage_wrighterimg)
    CircularImageView overpageWrighterimg;
    @BindView(R.id.overpage_authorname)
    TextView overpageAuthorname;
    @BindView(R.id.overpage_manimage)
    ImageView overpageManimage;
    @BindView(R.id.overpage_xiaomijiaonum)
    SuperButton overpageXiaomijiaonum;
    @BindView(R.id.overpage_jinjiaonum)
    SuperButton overpageJinjiaonum;
    @BindView(R.id.overpage_xiaomijiaobooknum)
    TextView overpageXiaomijiaobooknum;
    @BindView(R.id.overpage_jinjiaobooknum)
    TextView overpageJinjiaobooknum;
    @BindView(R.id.overpage_pinglunbooknum)
    TextView overpagePinglunbooknum;
    @BindView(R.id.overpage_fensiimg1)
    CircularImageView overpageFensiimg1;
    @BindView(R.id.overpage_fensiname1)
    TextView overpageFensiname1;
    @BindView(R.id.overpage_fensinum1)
    TextView overpageFensinum1;
    @BindView(R.id.overpage_fensi1)
    LinearLayout overpageFensi1;
    @BindView(R.id.overpage_nofensi1)
    TextView overpageNofensi1;
    @BindView(R.id.overpage_fensiimg2)
    CircularImageView overpageFensiimg2;
    @BindView(R.id.overpage_fensiname2)
    TextView overpageFensiname2;
    @BindView(R.id.overpage_fensinum2)
    TextView overpageFensinum2;
    @BindView(R.id.overpage_fensi2)
    LinearLayout overpageFensi2;
    @BindView(R.id.overpage_nofensi2)
    TextView overpageNofensi2;
    @BindView(R.id.overpage_fensiimg3)
    CircularImageView overpageFensiimg3;
    @BindView(R.id.overpage_fensiname3)
    TextView overpageFensiname3;
    @BindView(R.id.overpage_fensinum3)
    TextView overpageFensinum3;
    @BindView(R.id.overpage_fansi3)
    LinearLayout overpageFansi3;
    @BindView(R.id.overpage_nofensi3)
    TextView overpageNofensi3;
    @BindView(R.id.overpage_scview)
    View overpageScview;
    @BindView(R.id.overpage_recycle)
    RecyclerView overpageRecycle;
    @BindView(R.id.overpage_top)
    RelativeLayout overpageTop;

    private String bookId;
    private String bookName;
    private String bookWriterId;
    private String bookClassificationid;
    private ToSubcritDialog toSubcritDialog;
    private TotouweixiaomijinjiaoDialog totouweixiaomijinjiaoDialog;
    private NoBackgLodDialog noBackgLodDialog;
    private int jinchengNum = 0;
    private BookdatasBean.DataBean.BookdateBean bookDataInfoBean;
    private FensiRankBean fensiRankBean;
    private List<FensiRankBean.DataBean.ListBean> listBeans = new ArrayList<>();
    private BaseQuickAdapter adapter;
    private List<OverbookBean> dataBeanListyoulike = new ArrayList<>();
    private List<OverbookBean> dataBeanList = new ArrayList<>();
    private List<OverbookBean> overbookBeanList=new ArrayList<>();
    private LinearLayout.LayoutParams layoutParams;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read_overpage);
        ButterKnife.bind(this);
        overpageTop.getBackground().setAlpha(255);
        intView();
        intDate();
    }

    private void intDate() {
        getbookPinglunName();
        getBookdataBean();
        getBookfensi();
        getyoulike();
        getAuthorBook();
    }

    private void getAuthorBook() {
        OkHttpUtils.post(HttpManager.IP + "/book-AuthorAllBookInfo")
                .headers("token", "0")
                .params("authorId", bookWriterId)
                .params("startPage","1")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showNoBackDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismisNoBackDialog();
                        Gson gson = new Gson();
                        AuthorBean myBookBean = gson.fromJson(s, AuthorBean.class);
                        if (myBookBean.getReturnCode() == 200) {
                            dataBeanList .addAll(myBookBean.getData()) ;
                            adapter.notifyDataSetChanged();
                        }

                    }
                });
    }

    private void getyoulike() {
        OkHttpUtils.post(HttpManager.IP + "/stacks-bookFiltering")
                .params("bookClassificationid", bookClassificationid)
                .params("startPage", "1")
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showNoBackDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismisNoBackDialog();
                        Gson gson= new Gson();
                        YouLikeBean youLikeBean=gson.fromJson(s,YouLikeBean.class);
                        if (youLikeBean.getReturnCode()==200){
                            dataBeanListyoulike.addAll(youLikeBean.getData().getList());
                            overbookBeanList.clear();
                            overbookBeanList.addAll(dataBeanListyoulike);
                            adapter.notifyDataSetChanged();
                        }

                    }
                });

    }

    private void getBookfensi() {
        OkHttpUtils.get(HttpManager.IP + "/fans-bookFansWeek/" + bookId + "/" + 1)

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showNoBackDialog();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismisNoBackDialog();
                        Gson gson = new Gson();
                        try {
                            fensiRankBean = gson.fromJson(s, FensiRankBean.class);
                            if (fensiRankBean.getReturnCode() == 200) {
                                listBeans.clear();
                                listBeans.addAll(fensiRankBean.getData().getList());
                                toChageFensiView();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void toChageFensiView() {
        switch (listBeans.size()) {
            case 0:
                overpageFensi1.setVisibility(View.GONE);
                overpageFensi2.setVisibility(View.GONE);
                overpageFansi3.setVisibility(View.GONE);
                overpageNofensi1.setVisibility(View.VISIBLE);
                overpageNofensi2.setVisibility(View.VISIBLE);
                overpageNofensi3.setVisibility(View.VISIBLE);
                break;
            case 1:
                overpageFensi1.setVisibility(View.VISIBLE);
                overpageFensi2.setVisibility(View.GONE);
                overpageFansi3.setVisibility(View.GONE);
                overpageNofensi1.setVisibility(View.GONE);
                overpageNofensi2.setVisibility(View.VISIBLE);
                overpageNofensi3.setVisibility(View.VISIBLE);
                overpageFensinum1.setText(String.valueOf(listBeans.get(0).getFansCount()));
                overpageFensiname1.setText(listBeans.get(0).getUserName());
                Glide.with(this).load(listBeans.get(0).getUserHeadPortraitURL()).into(overpageFensiimg1);
                break;
            case 2:
                overpageFensi1.setVisibility(View.VISIBLE);
                overpageFensi2.setVisibility(View.VISIBLE);
                overpageFansi3.setVisibility(View.GONE);
                overpageNofensi1.setVisibility(View.GONE);
                overpageNofensi2.setVisibility(View.GONE);
                overpageNofensi3.setVisibility(View.VISIBLE);
                overpageFensinum1.setText(String.valueOf(listBeans.get(0).getFansCount()));
                overpageFensiname1.setText(listBeans.get(0).getUserName());
                Glide.with(this).load(listBeans.get(0).getUserHeadPortraitURL()).into(overpageFensiimg1);
                overpageFensinum2.setText(String.valueOf(listBeans.get(1).getFansCount()));
                overpageFensiname2.setText(listBeans.get(1).getUserName());
                Glide.with(this).load(listBeans.get(1).getUserHeadPortraitURL()).into(overpageFensiimg2);
                break;
            default:
                overpageFensi1.setVisibility(View.VISIBLE);
                overpageFensi2.setVisibility(View.VISIBLE);
                overpageFansi3.setVisibility(View.VISIBLE);
                overpageNofensi1.setVisibility(View.GONE);
                overpageNofensi2.setVisibility(View.GONE);
                overpageNofensi3.setVisibility(View.GONE);
                overpageFensinum1.setText(String.valueOf(listBeans.get(0).getFansCount()));
                overpageFensiname1.setText(listBeans.get(0).getUserName());
                Glide.with(this).load(listBeans.get(0).getUserHeadPortraitURL()).into(overpageFensiimg1);
                overpageFensinum2.setText(String.valueOf(listBeans.get(1).getFansCount()));
                overpageFensiname2.setText(listBeans.get(1).getUserName());
                Glide.with(this).load(listBeans.get(1).getUserHeadPortraitURL()).into(overpageFensiimg2);
                overpageFensinum3.setText(String.valueOf(listBeans.get(2).getFansCount()));
                overpageFensiname3.setText(listBeans.get(2).getUserName());
                Glide.with(this).load(listBeans.get(2).getUserHeadPortraitURL()).into(overpageFensiimg3);
                break;
        }
    }

    private void getBookdataBean() {
        OkHttpUtils.post(HttpManager.IP + "/getBookDataInfo")
                .params("bookid", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showNoBackDialog();

                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismisNoBackDialog();
                        Gson gson = new Gson();
                        bookDataInfoBean = gson.fromJson(s, BookdatasBean.DataBean.BookdateBean.class);
                        overpageXiaomijiaobooknum.setText("小米椒 " + bookDataInfoBean.getBookRecommend());
                        overpageJinjiaobooknum.setText("金椒 " + bookDataInfoBean.getGoldenTicket());
                    }
                });
    }

    private void dismisNoBackDialog() {
        jinchengNum -= 1;
        if (jinchengNum == 0 && noBackgLodDialog != null) {
            noBackgLodDialog.dismis();
        }
    }

    private void showNoBackDialog() {
        if (noBackgLodDialog == null) {
            noBackgLodDialog = new NoBackgLodDialog(ReadOverpageActivity.this, true);
        }
        noBackgLodDialog.show();
        jinchengNum += 1;
    }

    private void getbookPinglunName() {
        OkHttpUtils.get(HttpManager.IP + "/getBookCommentTotalCount/" + bookId)

                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        showNoBackDialog();
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        dismisNoBackDialog();
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                overpagePinglunbooknum.setText("评论 " + jsonObject.getInt("data"));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void intView() {
        bookId = getIntent().getStringExtra("bookId");
        bookName = getIntent().getStringExtra("bookName");
        bookWriterId = getIntent().getStringExtra("bookwriterId");
        bookClassificationid = getIntent().getStringExtra("bookClassificationid");
        overpageManimage.setImageResource(getIntent().getIntExtra("bookstatus", 0) == 0 ? R.drawable.overpagego : R.drawable.overpageover);
        overpageBookname.setText(bookName);
        overpageAuthorname.setText(getIntent().getStringExtra("bookwriterName"));
        Glide.with(this).load(getIntent().getStringExtra("bookwriterImage")).into(overpageWrighterimg);
        toshowmoneyNum();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        overpageRecycle.setLayoutManager(linearLayoutManager);
        overpageRecycle.setAdapter(adapter = new BaseQuickAdapter<OverbookBean, BaseViewHolder>(R.layout.recycelview_bookdatas, overbookBeanList) {
            @Override
            protected void convert(BaseViewHolder helper,OverbookBean item) {
                AutoUtils.autoSize(helper.itemView);
                Glide.with(mContext).load(item.getBookImage()).into((ImageView) helper.getView(R.id.recycle_bookImage));
                helper.setText(R.id.recycle_bookName, item.getBookName());
            }
        });
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(ReadOverpageActivity.this, BookDetailsActivity.class);
                intent.putExtra("bookId", String.valueOf(overbookBeanList.get(position).getBookId()));
                startActivity(intent);
            }
        });
    }

    private void toshowmoneyNum() {
        if (UserManageBean.isLogin()) {
            overpageXiaomijiaonum.setVisibility(View.VISIBLE);
            overpageJinjiaonum.setVisibility(View.VISIBLE);
            overpageJinjiaonum.setText(String.valueOf(UserManageBean.userBean.getUserGoldenTicket()));
            overpageXiaomijiaonum.setText(String.valueOf(UserManageBean.userBean.getUserRecommendTicket()));
        } else {
            overpageXiaomijiaonum.setVisibility(View.INVISIBLE);
            overpageJinjiaonum.setVisibility(View.INVISIBLE);
        }
    }

    @OnClick({R.id.overpage_goback, R.id.overpage_wrighterimg, R.id.overpage_excitationAuthor, R.id.overpage_xiaomijiao, R.id.overpage_jinjiao, R.id.overpage_pinglun, R.id.overpage_fensiimg1, R.id.overpage_fensiimg2, R.id.overpage_fensiimg3, R.id.overpage_lookmore, R.id.over_guessyoulike, R.id.overpage_authorbooks})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.overpage_goback:
                goBack();
                break;
            case R.id.overpage_wrighterimg:
                intent = new Intent(ReadOverpageActivity.this, UserCenterActivity.class);
                intent.putExtra("userId", bookWriterId);
                startActivity(intent);
                break;
            case R.id.overpage_excitationAuthor:
                if (toSubcritDialog == null) {
                    toSubcritDialog = new ToSubcritDialog(ReadOverpageActivity.this, bookId, bookName, bookWriterId);
                    toSubcritDialog.setListener(new ToSubcritDialog.Listener() {
                        @Override
                        public void subclickok() {
                            getBookdataBean();
                            getBookfensi();
                        }

                        @Override
                        public void subnologin() {
                            Intent intent = new Intent(ReadOverpageActivity.this, LoginActivity.class);
                            startActivity(intent);
                        }
                    });
                } else {
                    toSubcritDialog.show();
                }

                break;
            case R.id.overpage_xiaomijiao:
                toshowgiveDialog(0);
                break;
            case R.id.overpage_jinjiao:
                toshowgiveDialog(1);
                break;
            case R.id.overpage_pinglun:
                intent = new Intent(ReadOverpageActivity.this, AuthShuPingActivity.class);
                intent.putExtra("bookId", bookId);
                intent.putExtra("bookName", bookName);
                startActivity(intent);
                break;
            case R.id.overpage_fensiimg1:
                intent = new Intent(ReadOverpageActivity.this, UserCenterActivity.class);
                intent.putExtra("userId", String.valueOf(listBeans.get(0).getUserId()));
                startActivity(intent);
                break;
            case R.id.overpage_fensiimg2:
                intent = new Intent(ReadOverpageActivity.this, UserCenterActivity.class);
                intent.putExtra("userId", String.valueOf(listBeans.get(1).getUserId()));
                startActivity(intent);
                break;
            case R.id.overpage_fensiimg3:
                intent = new Intent(ReadOverpageActivity.this, UserCenterActivity.class);
                intent.putExtra("userId", String.valueOf(listBeans.get(2).getUserId()));
                startActivity(intent);
                break;
            case R.id.overpage_lookmore:
                intent = new Intent(ReadOverpageActivity.this, FansRankActivity.class);
                intent.putExtra("bookId", bookId);
                startActivity(intent);
                break;
            case R.id.over_guessyoulike:
               overbookBeanList.clear();
               overbookBeanList.addAll(dataBeanListyoulike);
                adapter.notifyDataSetChanged();
                layoutParams = new LinearLayout.LayoutParams(overpageScview.getLayoutParams());
                layoutParams.width=ScreenUtils.getNum(ReadOverpageActivity.this,70);
                layoutParams.leftMargin = ScreenUtils.getNum(ReadOverpageActivity.this,5);
                overpageScview.setLayoutParams(layoutParams);
                break;
            case R.id.overpage_authorbooks:
                overbookBeanList.clear();
                overbookBeanList.addAll(dataBeanList);
                adapter.notifyDataSetChanged();
                layoutParams = new LinearLayout.LayoutParams(overpageScview.getLayoutParams());
                layoutParams.width=ScreenUtils.getNum(ReadOverpageActivity.this,120);

                layoutParams.leftMargin = ScreenUtils.getNum(ReadOverpageActivity.this,90);
                overpageScview.setLayoutParams(layoutParams);

                break;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        overpageTop.getBackground().setAlpha(255);
    }

    //i=0弹出给小米椒的dialog，1是弹出给金椒的dialog
    private void toshowgiveDialog(int i) {
        if (totouweixiaomijinjiaoDialog == null) {
            totouweixiaomijinjiaoDialog = new TotouweixiaomijinjiaoDialog(ReadOverpageActivity.this, bookId, bookName, bookWriterId);
            totouweixiaomijinjiaoDialog.setListener(new TotouweixiaomijinjiaoDialog.Listener() {
                @Override
                public void subclickok() {
                    getBookdataBean();
                    getBookfensi();
                }

                @Override
                public void clickquhao() {
                    Intent intent = new Intent(ReadOverpageActivity.this, SelectquhaoActivity.class);
                    startActivityForResult(intent, CodeManager.Binding_read);
                }

                @Override
                public void subnologin() {
                    Intent intent = new Intent(ReadOverpageActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            });
        }
        totouweixiaomijinjiaoDialog.show(i);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CodeManager.Binding_read && CodeManager.Binding_read == resultCode) {
            if (totouweixiaomijinjiaoDialog != null) {
                totouweixiaomijinjiaoDialog.setQuhao(data.getStringExtra("countryNumber"));
            }
        }
    }
}
